#!user/bin/env python3
# -- coding: utf-8 --
import time
from PIL import Image

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
import requests

# 2.使用selenium打开注册页面，并截图 【切记最大化】
driver = webdriver.Edge(
    service=Service(r'C:\Users\Administrator\PycharmProjects\web_crawler\MicrosoftWebDriver.exe'))
driver.get('https://www.ctrip.com/')
driver.maximize_window()
time.sleep(2)
# 点击注册
driver.find_element(By.XPATH, '//*[@class="person-text nav-per"]/span').click()
# 点击同意“携程用户注册协议和隐私政策”
driver.find_element(By.CSS_SELECTOR, '.reg_btn.reg_agree').click()
# 定位滑块按钮
drag_button = driver.find_element(By.CSS_SELECTOR, '.cpt-drop-btn')
# 定位滑块区域
drag_button_area = driver.find_element(By.CSS_SELECTOR, '.cpt-bg-bar')
# 拖动滑块
time.sleep(3)
ActionChains(driver).drag_and_drop_by_offset(drag_button, drag_button_area.size['width'],
                                             drag_button_area.size['height']).perform()
time.sleep(3)
# 网页截图
driver.save_screenshot('./page.png')
# 3.确定验证码图片区域位置和大小
verification_img = driver.find_element(By.CSS_SELECTOR, ' .cpt-choose-box.cpt-choose-box-pop')
coordinate = verification_img.location  # 坐标
size = verification_img.size
# print(size)
# 4.验证码图片左上角和右下角坐标
coordinate_all = (int(coordinate['x']), int(coordinate['y']), int(coordinate['x']) + int(size['width']),
                  int(coordinate['y']) + int(size['height']))
# print(coordinate_all)
# 5.实例化一个Image对象 【加载截图，指定裁剪后的图片名字】
open = Image.open('./page.png')
verification_page_name = './verification.png'
# 6.使用crop根据指定区域（左上到右下两点坐标）进行图片的裁剪
crop = open.crop(coordinate_all)
crop.save(verification_page_name)
